package org.jason.common.exception;

import org.jason.model.common.dtos.ResponseResult;
import org.jason.model.common.enums.HttpCodeEnum;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;

@RestControllerAdvice
public class MyExceptionHandler {
    /**
     * 处理不可控异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public ResponseResult<?> exception(Exception e) {
        e.printStackTrace();
        return ResponseResult.get(HttpCodeEnum.SERVER_ERROR, e.getMessage());
    }

    /**
     * 处理可控异常  自定义异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(ServiceException.class)
    public ResponseResult<?> exception(ServiceException e) {
        return ResponseResult.get(e.getHttpCodeEnum(), e.getMsg());
    }

    /**
     * param参数异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BindException.class)
    public ResponseResult<?> exception(BindException e) {
        String s = Objects.requireNonNull(e.getFieldError()).getDefaultMessage();
        return ResponseResult.get(HttpCodeEnum.PARAM_INVALID, s);
    }

    /**
     * body参数异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseResult<?> exception(MethodArgumentNotValidException e) {
        String s = Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage();
        return ResponseResult.get(HttpCodeEnum.PARAM_INVALID, s);
    }
}
